import React from "react";
import { Form, Input, InputNumber, Select, Button, Space, Spin, TimePicker } from "antd";
import TheUpload from "@/components/TheUpload";
import TheDialog from "@/components/TheDialog";
import "../style/style.less";
import { apiStoreInfoDetail, apiStoreServiceLabelList, apiStoreInfoEdit } from '@/request/settings'
import _ from 'lodash';
import TheImage from '@/components/TheImage'

class Settings extends React.Component {
  inputRef = React.createRef();
  state = {
    visible: false,
    mapData: null,
    loading: false,
    time: []
  };
  async componentDidMount() {
    await this.getLabelList()
    await this.getData()
    const that = this;
    window.addEventListener("message", function (event) {
      if (event) {
        if (event.data.latlng) {
          event.data.latlng.lat = `${event.data.latlng.lat}`.substring(
            0,
            `${event.data.latlng.lat}`.indexOf(".") + 7
          );
          event.data.latlng.lng = `${event.data.latlng.lng}`.substring(
            0,
            `${event.data.latlng.lng}`.indexOf(".") + 7
          );
        }
        that.setState(
          {
            mapData: event.data,
          }
        );
      }
    });
  }

  getLabelList = async () => {
    let res = await apiStoreServiceLabelList({})
    if (res.code === 0 && res.data) {
      let labelList = res.data.map(v => {
        return {
          value: v.serviceLabelId,
          label: v.storeServiceName
        }
      })
      this.setState({ labelList })
    }
  }

  getData = async () => {
    this.setState({ loading: true })
    let res = await apiStoreInfoDetail()
    if (res.code === 0 && res.data) {
      let data = res.data
      let storeShowFileList = this.getFileList(data.storeShowFile)
      let storeEnvironmentList = this.getFileList(data.storeEnvironment)
      let storeLogoList = this.getFileList(data.storeLogo)
      let businessLicenseList = this.getFileList(data.businessLicense)
      let corporateIdentityCardPositiveList = this.getFileList(data.corporateIdentityCardPositive)
      let corporateIdentityCardBackList = this.getFileList(data.corporateIdentityCardBack)
      let serviceLabelIds = data.serviceLabelIds && data.serviceLabelIds.split(',')
      let time = [React.$moment(data.storeOpenTime, 'HH:mm'), React.$moment(data.storeCloseTime, 'HH:mm')]
      this.setState({
        storeShowFileList,
        storeEnvironmentList,
        storeLogoList,
        businessLicenseList,
        corporateIdentityCardPositiveList,
        corporateIdentityCardBackList,
        serviceLabelIds,
        addressLnt: data.addressLnt,
        addressLat: data.addressLat,
        loading: false,
        time: [data.storeOpenTime, data.storeCloseTime]
      }, () => {
        this.formRef.setFieldsValue({ ...data, serviceLabelIds, time })
        this.inputRef.current.value = data.addressMapLocation
      })
    } else {
      this.setState({
        loading: false
      })
    }
  }

  getFileList = (value) => {
    if (value && _.isString(value)) {
      return value.split(',').map((v, i) => {
        return {
          uid: i,
          status: 'done',
          name: `image-${i}`,
          url: v
        }
      })
    } else {
      return []
    }
  }

  getFileResult = (value, name) => {
    if (value && value.length) {
      let ids = value.map(v => {
        if (v.response && v.response.code === 0) {
          return v.response.data
        } else if (v.url) {
          return v.url
        } else {
          return ''
        }
      }).join(',')
      this.formRef.setFieldsValue({ [name]: ids });
    } else {
      this.formRef.setFieldsValue({ [name]: "" });
    }
  };

  setAreaData = (data) => {
    const { provinceName, cityName, areaName } = data;
    this.formRef.setFieldsValue({ address: data });
    this.setState({
      provinceName,
      cityName,
      areaName,
    });
  };

  selectAddress = () => {
    this.setState({
      visible: true,
    });
  };

  handleCancel = () => {
    this.setState(
      {
        visible: false,
      },
      () => {
        const { mapData } = this.state;
        if (mapData) {
          this.formRef.setFieldsValue({
            addressMapLocation: mapData.poiname,
            addressLat: mapData.latlng.lat,
            addressLnt: mapData.latlng.lng,
            addressDetail: mapData.poiaddress,
          });
          this.inputRef.current.value = mapData.poiname;
          this.setState({ inputValue: mapData.poiname });
        }
      }
    );
  };
  selectChange = value => {
    this.setState({ serviceLabelIds: value })
  }
  goHome = () => {
    this.props.history.push('/home')
  }
  onFinish = async value => {
    this.setState({ loading: true })
    value.serviceLabelIds = value.serviceLabelIds.join(',')
    value.storeOpenTime = this.state.time[0]
    value.storeCloseTime = this.state.time[1]
    delete (value.time)
    let res = await apiStoreInfoEdit({ ...value })
    if (res.code === 0) {
      React.$message({
        type: 'info',
        content: '修改成功'
      })
      this.setState({ loading: false })
    } else {
      this.setState({ loading: false })
    }
  }
  timeChange = (time, timeString) => {
    this.setState({ time: timeString })
  }
  render() {
    const { labelList, visible, storeShowFileList, storeEnvironmentList, storeLogoList, businessLicenseList, corporateIdentityCardPositiveList, corporateIdentityCardBackList, addressLat, addressLnt, loading } = this.state;
    const url = addressLat && addressLnt ?
      `https://mapapi.qq.com/web/mapComponents/locationPicker/v/index.html?search=1&type=1&coord=${addressLat},${addressLnt}&key=ZYPBZ-NQNLF-HHUJC-NVLRM-OFL3Q-EBBL2&referer=myapp` :
      `https://mapapi.qq.com/web/mapComponents/locationPicker/v/index.html?search=1&type=1&coord=45.80216%2C126.5358&key=ZYPBZ-NQNLF-HHUJC-NVLRM-OFL3Q-EBBL2&referer=myapp`
    return (
      <div className="settings-box">
        <Spin spinning={loading}>
          <Form onFinish={this.onFinish} ref={(ref) => (this.formRef = ref)}>
            <div className="title">门店信息</div>
            <Form.Item
              rules={[{ required: true }]}
              label="门店名称"
              name={'storeName'}>
              <Input disabled={true} placeholder="请输入门店名称" style={{ width: 200 }} />
            </Form.Item>
            <Form.Item
              rules={[{ required: true }]}
              label="联系人"
              name={'storeContacts'}>
              <Input placeholder="请输入联系人" style={{ width: 200 }} />
            </Form.Item>
            <Form.Item
              rules={[{ required: true }]}
              label="联系电话"
              name={'userMobile'}>
              <Input placeholder="请输入联系电话" style={{ width: 200 }} />
            </Form.Item>
            <Form.Item
              rules={[{ required: true }]}
              label="门店标签"
              name={'serviceLabelIds'}>
              <Select
                placeholder="请选择门店标签"
                mode="multiple"
                allowClear
                style={{ width: 200 }}
                // value={serviceLabelIds}
                options={labelList}
                onChange={this.selectChange}
              />
            </Form.Item>
            <Form.Item label="营业时间" rules={[{ required: true }]} name="time">
              <TimePicker.RangePicker onChange={this.timeChange} format={'HH:mm'} />
            </Form.Item>
            <Form.Item
              rules={[{ required: true }]}
              label="门店图片"
              name={'storeShowFile'}>

              {!_.isEmpty(storeShowFileList) && <TheUpload fileList={storeShowFileList} getFileResult={value => this.getFileResult(value, 'storeShowFile')} len={1} />}
            </Form.Item>
            <Form.Item
              rules={[{ required: true }]}
              label="店铺环境"
              name={'storeEnvironment'}>

              {!_.isEmpty(storeEnvironmentList) && <TheUpload fileList={storeEnvironmentList} getFileResult={value => this.getFileResult(value, 'storeEnvironment')} len={4} />}
            </Form.Item>
            <Form.Item
              rules={[{ required: true }]}
              label="店铺logo"
              name={'storeLogo'}>

              {!_.isEmpty(storeLogoList) && <TheUpload fileList={storeLogoList} getFileResult={value => this.getFileResult(value, 'storeLogo')} len={1} />}
            </Form.Item>
            <div className="title">资质信息</div>
            {/* <Form.Item label="门店所在地区" name={'address'}>
            <TheArea
              ref={(ref) => (this.addressRef = ref)}
              setAreaData={this.setAreaData}
            />
          </Form.Item> */}
            <Form.Item
              rules={[{ required: true }]}
              name={"addressMapLocation"}
              label="门店地址">
              <Space>
                <input
                  className="address-input"
                  ref={this.inputRef}
                  placeholder="请在地图上选点"
                />
                <Button onClick={this.selectAddress}>打开地图</Button>
              </Space>
            </Form.Item>
            <Form.Item
              rules={[{ required: true }]}
              name={"addressLnt"}
              label="经度">
              <InputNumber placeholder="请输入经度" style={{ width: 200 }} />
            </Form.Item>
            <Form.Item
              rules={[{ required: true }]}
              name={"addressLat"}
              label="纬度">
              <InputNumber placeholder="请输入纬度" style={{ width: 200 }} />
            </Form.Item>
            <Form.Item
              name={"addressDetail"}
              label="详细地址(选填)">
              <Input placeholder="请输入详细地址" style={{ width: 400 }} />
            </Form.Item>
            <Form.Item
              rules={[{ required: true }]}
              label="营业执照"
              name={'businessLicense'}>

              {/* {!_.isEmpty(businessLicenseList) && <TheUpload fileList={businessLicenseList} getFileResult={value => this.getFileResult(value, 'businessLicense')} len={1} />} */}
              {
                !_.isEmpty(businessLicenseList) && businessLicenseList.map((v, i) => {
                  return <TheImage height={80} width={80} src={v.url} />
                })
              }
            </Form.Item>
            <div className="title">法人信息</div>
            <Form.Item
              rules={[{ required: true }]}
              labelCol={{ sapn: 3 }}
              label="法人身份证正面"
              name={'corporateIdentityCardPositive'}>

              {/* {!_.isEmpty(corporateIdentityCardPositiveList) && <TheUpload fileList={corporateIdentityCardPositiveList} getFileResult={value => this.getFileResult(value, 'corporateIdentityCardPositive')} len={1} />} */}
              {
                !_.isEmpty(corporateIdentityCardPositiveList) && corporateIdentityCardPositiveList.map((v, i) => {
                  return <TheImage height={80} width={80} src={v.url} />
                })
              }
            </Form.Item>
            <Form.Item
              rules={[{ required: true }]}
              labelCol={{ sapn: 3 }}
              label="法人身份证背面"
              name={'corporateIdentityCardBack'}>

              {/* {!_.isEmpty(corporateIdentityCardBackList) && <TheUpload fileList={corporateIdentityCardBackList} getFileResult={value => this.getFileResult(value, 'corporateIdentityCardBack')} len={1} />} */}
              {
                !_.isEmpty(corporateIdentityCardBackList) && corporateIdentityCardBackList.map((v, i) => {
                  return <TheImage height={80} width={80} src={v.url} />
                })
              }
            </Form.Item>
            <Form.Item
              rules={[{ required: true }]}
              labelCol={{ sapn: 3 }}
              label="收款账号(支付宝)"
              name={'alipayAccount'}>
              <Input placeholder="请输入收款账号" style={{ width: 200 }} />
            </Form.Item>
            <Form.Item>
              <div style={{ display: "flex", justifyContent: "center" }}>
                <Space>
                  <Button onClick={this.goHome}>取消</Button>
                  <Button type="primary" htmlType="submit">保存</Button>
                </Space>
              </div>
            </Form.Item>
          </Form>
        </Spin>
        <TheDialog
          title=""
          width={500}
          handleCancel={this.handleCancel}
          visible={visible}
          footer={null}
        >
          <iframe
            title="map"
            style={{
              width: 400,
              height: 700,
              border: "1px solid #fafafa",
              marginLeft: "20px",
            }}
            src={url}
          />
        </TheDialog>
      </div>
    );
  }
}

export default Settings;
